import Base64 from '@/utils/base64'
import {
  getTokenMsgArr
} from '@/config/apiServe/fetch-config.js'
import {
  getBlocksInfo,
} from '@/config/apiServe/new-rpc.js'
export default {
  data() {
    return {
      priceTimer: 0,
      btyInfo: {
        perTxCount: 0,
        perTime: 0,
        rmb: 0,
        usd: 0,
        totalSum: 370377328,
        txCount: 13256528
      }
    }
  },
  computed: {
    maxHash() {
      return this.$store.state.maxHash;
    },
    maxHeight() {
      return this.$store.state.maxHeight;
    }
  },
  watch: {
    maxHash(hash) {
      this.hexCharCodeToStr(hash)
      this.getChainInfo()
      this.getBtyValue()
    }
  },
  mounted() {
    this.getBtyValue()
  },
  methods: {
    // 获取区块信息
    getChainInfo() {
      let infos = [{
        height: [2270000, this.maxHeight]
      }]
      getBlocksInfo(infos).then(res => {
        if (res.error === null) {
          let fatherBlock = res.result[0]
          let lastBlock = res.result[1]
          this.btyInfo.perTime = (lastBlock.time - fatherBlock.time) / (this.maxHeight - 2270000)
          this.btyInfo.perTxCount = (lastBlock.tx_count - fatherBlock.tx_count) / (lastBlock.time - fatherBlock.time)
        }
      })
    },
    // 获取BTY价值
    getBtyValue() {
      getTokenMsgArr(['BTY']).then(data => {
        if (data.code === 0) {
          this.btyInfo.rmb = data.data[0].rmb;
          this.btyInfo.usd = data.data[0].usd;
        }
      })
    },
    //获取BTY交易总数
    getBTYtradeSum(hash) {
      this.Rpc.queryTotalFee([`${hash}`]).then(data => {
        if (data.error === null) {
          // 2270000分叉区块，收益30 --> 8
          this.btyInfo.totalSum =
            this.maxHeight > 2269999 ?
            367369978 + 8 * this.maxHeight - data.result.fee / 100000000 :
            317430000 + 30 * this.maxHeight - data.result.fee / 100000000;
          this.btyInfo.txCount = data.result.txCount;
        } else {
          this.$notify({
            title: this.$t('components.tip'),
            message: data.error,
            type: "warning"
          });
        }
      });
    },
    // 16进制转换处理
    hexCharCodeToStr(hexCharCodeStr) {
      let num = hexCharCodeStr;
      let trimedStr = num.trim();
      let rawStr =
        trimedStr.substr(0, 2).toLowerCase() === "0x" ?
        trimedStr.substr(2) :
        trimedStr;
      let len = rawStr.length;
      if (len % 2 !== 0) {
        alert("Illegal Format ASCII Code!");
        return "";
      }
      let curCharCode;
      let resultStr = [];
      for (let i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
        resultStr.push(String.fromCharCode(curCharCode));
      }
      //转码ASCII——base64
      let b = new Base64();
      let str = b.encode(`TotalFeeKey:${resultStr.join("")}`);
      this.getBTYtradeSum(str)
    }
  },
  // beforeDestroy() {
  //   clearInterval(this.priceTimer);
  // }
}